class TreeNode {
  val: unknown;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val: unknown, left: TreeNode | null, right: TreeNode | null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

const tree = new TreeNode(1, 
  new TreeNode(2, 
    null, 
    new TreeNode(4, 
      null, 
      null
    )
  ), 
  new TreeNode(3, 
    null, 
    null
  )
);

const layerOrder = (root: TreeNode) => {
  const queue: Array<TreeNode | null> = [root];
  const result: Array<Array<TreeNode | null>> = [];

  while (queue.length && queue.some((item) => item !== null)) {
    // 取出队列长度快照，表示当前要处理的下一层的节点数量，循环处理每一个节点
    const currentLayerNodeCount = queue.length;

    // 需要注意的是：在构造每一层的遍历结果时，不能直接新建一个空数组然后push，因为对于空节点，仍然需要保留其位置信息，所以需要创建长度精确的数组，赋值时也需要对精确位置进行赋值
    const currentLayerResult = new Array(currentLayerNodeCount).fill(null);

    for (let i = 0; i < currentLayerNodeCount; i++) {
      const currentNode = queue.shift();
      // 如果节点存在，左右子节点入队 & 构造result
      // 如果节点不存在，result.push(null)表示
      if (currentNode) {
        queue.push(currentNode.left, currentNode.right);
        currentLayerResult[i] = currentNode.val;
      } else {
        queue.push(null, null);
        currentLayerResult[i] = null;
      }
    }

    result.push(currentLayerResult);
  }

  return result;
};

console.log(layerOrder(tree));